package com.bigger.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bigger.dto.AddVIPDTO;
import com.bigger.dto.UserPageDTO;
import com.bigger.entity.User;
import com.bigger.mapper.UserMapper;
import com.bigger.result.PageResult;
import com.bigger.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult<User> page(UserPageDTO userPageDTO) {
        Page<User> page = new Page<>(userPageDTO.getPage(), userPageDTO.getPageSize());
        QueryWrapper<User> wrapper = new QueryWrapper<User>()
                .eq(userPageDTO.getUsername() != null && !userPageDTO.getUsername().isEmpty()
                        , "username", userPageDTO.getUsername());
        Page<User> userPage = userMapper.selectPage(page, wrapper);
        if (userPage.getRecords().isEmpty()) {
            page = Page.of(1, userPageDTO.getPageSize());
            userPage = userMapper.selectPage(page, wrapper);
        }
        return new PageResult<>(userPage.getTotal(), userPage.getRecords());
    }

    @Override
    public void addVIP(AddVIPDTO addVIPDTO) {
        User user = new User();
        user.setId(addVIPDTO.getId());
        LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        if (addVIPDTO.getYear() != null) {
            now=now.plusYears(addVIPDTO.getYear());
        }
        if (addVIPDTO.getMonth() != null) {
            now=now.plusMonths(addVIPDTO.getMonth());
        }
        if (addVIPDTO.getDay() != null) {
            now=now.plusDays(addVIPDTO.getDay());
        }
        user.setExpirationTime(now);
        user.setIsVIP(User.IS_VIP);
        userMapper.updateById(user);
    }

    @Override
    public void delete(Long id) {
        userMapper.cancelVIP(id);
    }
}

